<template>
    <div>
        <div class="gva-table-box">
            <LTable
                :columns="columns"
                :tableData="tableData"
                :maxHeight="'calc(100vh - 226px)'"
                :pages="pages"
                @changePages="changePages"
                @updateMultipleSelection="handleSelectionChange"
                :searchArr="searchArr"
                :isSearch="true"
                @rowDblclick="row => openEditDialog(row, true)"
                @onSubmit="onSubmit"
            >
                <template #action>
                    <div class="gva-btn-list">
                        <el-button
                            type="primary"
                            icon="plus"
                            @click="openCreateDialog"
                            >新增</el-button
                        >
                        <el-button
                            type="primary"
                            icon="delete"
                            :disabled="!multipleSelection.length"
                            @click="deleteRow"
                            >删除</el-button
                        >
                    </div>
                </template>
            </LTable>
        </div>

        <!-- 新增审批流 -->
        <el-dialog
            v-if="addVisible"
            v-model="addVisible"
            destroy-on-close
            width="50%"
            title="新增审批流"
        >
            <el-form
                ref="addFormRef"
                :model="addForm"
                :rules="addFormRules"
            >
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="审批流名称：" prop="name">
                            <el-input
                                v-model="addForm.name"
                                placeholder="输入审批流名称"
                                :clearable="true"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="说明：" prop="description">
                             <textarea
                                v-model="addForm.description"
                                :rows="5"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="绑定模块：" prop="module_name">
                            <el-select v-model="addForm.module_name" placeholder="请选择" style="width: 240px">
                                <el-option
                                    v-for="item in options"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleAddWorkflow"
                        >确定</el-button
                    >
                    <el-button
                        @click="
                            (addForm = {}),
                                (addVisible = false)
                        "
                        >取消</el-button
                    >
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {
  createWorkflowDef,
  deleteWorkflowDef,
  deleteWorkflowDefByIds,
  updateWorkflowDef,
  findWorkflowDef,
  getWorkflowDefList
} from '@/api/workflow'

// 全量引入格式化工具 请按需保留
import {
    getDictFunc,
    formatDate,
    formatBoolean,
    filterDict,
    ReturnArrImg,
    onDownloadFile,
} from "@/utils/format";
import LTable from "@/components/LTable/LTable.vue";
// import searchForm from "@/components/searchForm/searchForm.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, onMounted, watchEffect } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { useDict } from "@/utils/dictionary";
const dict = ref({});
const { t: il8n } = useI18n();

defineOptions({
    name: "wworkflow",
});
// 使用 useRoute 函数获取当前路由信息
const router = useRouter();
const options = ref([])
// 验证规则
const rule = reactive({});
const values = ref();
const elFormRef = ref();
const elSearchFormRef = ref();

// =========== 表格控制部分 ===========

const tableData = ref([]);
const searchInfo = ref({});

const pages = ref({
    page: 1,
    pageSize: 20,
    total: 0,
});

const addVisible = ref(false)
const addForm = ref({})
const addFormRules = ref({})
const addFormRef = ref()


// ======查询数据======
const searchArr = ref([]);
// ======表格头部数据======
const columns = ref([]);

watchEffect(() => {

    const newSearchArr = [
        {
            prop: "name",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "input",
        },
        {
            prop: "description",
            show: true,
            value: "",
            type: "",
        },
        {
            prop: "CreatedAt",
            label: il8n("createdAt.label"),
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "datetimerange",
        },
        {
            prop: "createUser",
            label: "创建人",
            show: true,
            value: "",
            type: "input",
        },
        {
            prop: "UpdatedAt",
            label: "更新时间",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "datetimerange",
        },
        {
            prop: "updateUser",
            label: "更新人",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "input",
        },
        {
            prop: "module_title",
            label: "绑定模块",
            show: true, // 通过 show 来控制列的展示或隐藏
            value: "",
            type: "input",
        },
    ];
    searchArr.value = [...newSearchArr];

    const newColumns = [
        {
            prop: "name",
            fixedWidth: 260,
            label: "审批流名称",
            show: true, // 通过 show 来控制列的展示或隐藏
            filter: true,
            // slot: "firstOrderNum",
            tableColumnProps: {
                fixed: "left",
            },
        },
        {
            prop: "description",
            label: "说明",
            show: true,
        },
        {
            prop: "CreatedAt",
            label: il8n("createdAt.label"),
            show: true
        },
        {
            prop: "createUser",
            label: "创建人",
            show: true
        },
        {
            prop: "UpdatedAt",
            label: il8n("updatedAt.label"),
            show: true
        },
        {
            prop: "updateUser",
            label: "更新人",
            show: true
        },
        {
            prop: "module_title",
            label: "绑定模块",
            show: true, // 通过 show 来控制列的展示或隐藏
        },
    ];
    columns.value = [...newColumns];
});

// 搜索
const onSubmit = (val) => {
    searchInfo.value = {
        ...val,
    };
    pages.value.page = 1;
    pages.value.pageSize = 20;
    getTableData();
};


// 查询
const getTableData = async () => {
    const params = {
        ...pages.value,
        ...searchInfo.value,
    }
    // 查询
    const table = await getWorkflowDefList(params)
    if (table.code === 0) {
        tableData.value = table.data.list.map(m => { 
            return {
                ...m,
                CreatedAt: m.CreatedAt ? formatDate(m.CreatedAt) : "",
                UpdatedAt: m.UpdatedAt ? formatDate(m.UpdatedAt) : ""
            }
        })
    }
};

// ============== 表格控制部分结束 ===============

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 打开弹窗
const openCreateDialog = () => {
    // 打开弹窗
    addVisible.value = true
    addForm.value = {}
   
};

const openEditDialog = (row, isView) => {
    // 打开弹窗
    window.open("/static/Workflow/dist/?workFlowDefId=" + row.ID)
};

onMounted(async () => {
    getTableData();
       // 获取字典
        useDict("workflow_bind_module",).then((d) => {
        // 字典列表
         options.value =d.workflow_bind_module
    });
});


function changePages(currentPages) {
    pages.value = {
        ...pages.value,
        ...currentPages,
    };
    getTableData();
}


function handleAddWorkflow() {
    addFormRef.value.validate(async valid => {
        if (valid) {
            let datas = {...addForm.value}
            if(datas.module_name) {
                datas.module_title = options.value.filter(item=>item.value==datas.module_name)[0].label
            }
            const res = await createWorkflowDef(datas)
            if (res.code === 0) {
                ElMessage({
                    type: "success",
                    message: "添加成功",
                });
                getTableData()
                addVisible.value = false
            }
        }
    })
}

// 删除行
const deleteRow = async () => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const IDs = [];
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: "warning",
                message: "请选择要删除的数据",
            });
            return;
        }
        multipleSelection.value &&
            multipleSelection.value.map((item) => {
                IDs.push(item.ID);
            });
        const res = await deleteWorkflowDefByIds({ IDs });
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "删除成功",
            });
            if (tableData.value.length === IDs.length && pages.value.page > 1) {
                pages.value.page--;
            }
            getTableData();
        }
    });
};

</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
</style>
